<?php
	require_once("db_connect.php");
	require_once("safeFunctions.php");

	function getRights(&$db, $url = "#4711") {
		$username = $_SESSION["username"];
		//if no real value on $url, we get it from URI
		if($url === "#4711") {
			$url = explode("=", $_SERVER['REQUEST_URI']);
		
			if(sizeof($url) === 1) {
				$url = "start";
			}else{
				$url = explode("&", $url[1])[0];
			}
		}
		//initialize variables used for SQL-query for getting all rights for a page
		$rights = 0;
		$url = safety($url);
		$parentId = $url;
		//get the pageId and its parentId from DB
		if(is_numeric($url)) {
			$pageQuery = mysqli_query($db, "SELECT id, parentId FROM pages WHERE id='$url'");
		}else{
			$pageQuery = mysqli_query($db, "SELECT id, parentId FROM pages WHERE name='$url'");
		}
		//if we cannot connect to DB we give error
		if(!$pageQuery) {
			echo "db error trying to find page";
			return 0;
		}

		
		
		//while we do not have a parent, we get information of a page from DB to form the hierarchy
		while(!is_null($parentId)) {
			
			//get information from the DB-query
			$pageRow = $pageQuery->fetch_assoc();
			$id = $pageRow["id"];
			$parentId = $pageRow["parentId"];
			
			//SQL query that JOINS two DB to get the rights for a specific page for a single user
			$rightsQuery = mysqli_query($db, "SELECT rights FROM group_rights JOIN users ON group_rights.groupId = users.rightsId WHERE group_rights.pageId = '$id' AND users.username = '$username' LIMIT 1");
			
			//we couldnt get any rights for a specific page
			if(!$rightsQuery) {
				echo "db error trying to find rights for a page";
				return $rights;
			}	
		
			$rightsRow = $rightsQuery->fetch_assoc();
		
			//check if we got any rights, it is possible there are no defined rights for a page
			if(isset($rightsRow["rights"])){
				//calulcate highest rights-value of all the pages.
				$rights |= $rightsRow["rights"];
			}
			
			$pageQuery = mysqli_query($db, "SELECT id, parentId FROM pages WHERE id='$parentId'");
			
		}
		
		return $rights;
	}
	
	function canSeeAdmin(&$db) {
		$query = mysqli_query($db, "SELECT * FROM users JOIN user_groups ON users.rightsId = user_groups.id WHERE users.id = {$_SESSION["id"]} AND (user_groups.name LIKE '%teacher%' OR user_groups.name = 'admin')");
		return ($query->num_rows > 0);
		
	}

?>